﻿using System.Text;
using Microsoft.AspNetCore.Http;

namespace sgf.server
{
    public abstract class HttpMsgHandler<T> : IHttpMsgHandler
    {
        public async Task Run(BusActor busActor, HttpRequest request, HttpResponse response)
        {
            var body = await new StreamReader(request.Body).ReadToEndAsync();
            var msg = body.ToObj<T>();
            var responseMsg = await Handle(busActor, msg);
            var responseBody = responseMsg.ToJson();
            var buffer = Encoding.UTF8.GetBytes(responseBody);
            response.ContentType = "application/json";
            response.ContentLength = buffer.Length;
            await response.Body.WriteAsync(buffer);
            // response.ContentLength64 = buffer.Length;
            // await response.OutputStream.WriteAsync(buffer);
            // response.Close();
        }

        public abstract String GetPrefix();

        protected abstract Task<HttpMsgResponse> Handle(BusActor busActor, T msg);
    }
}